package dragon.social.controller;

import dragon.social.dto.SocialUserInfo;
import dragon.social.entity.Userinfo;
import dragon.social.mapper.UserinfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionKey;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    ProviderSignInUtils providerSignInUtils;

    @Autowired
    UserinfoMapper userinfoMapper;

    @Autowired
    PasswordEncoder passwordEncorder;

    /**
     * 注册页/绑定社交账号页
     * @param userinfo
     * @param request
     * @return
     */
    @RequestMapping("/regist")
    public String regist(Userinfo userinfo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletWebRequest servletWebRequest = new ServletWebRequest(request);
        SocialUserInfo socialInfo = getSocialInfo(request);
        userinfo.setDisplayName(socialInfo.getNickName());
        userinfo.setPassword(passwordEncorder.encode(userinfo.getPassword()));
        userinfoMapper.insert(userinfo);
        Long userId = userinfo.getUserId();
        //把user id插入到userconnection表中
        providerSignInUtils.doPostSignUp(userId + "", servletWebRequest);
        //这里引发跳转会导致回去login。我估计是因为插入userconnection表，并不等于完成了登录。
//        response.sendRedirect("/index");
        //因此比较好的方法是，带参数触发登录url
        return null;
    }

    /**
     * 获取social授权后的资料
     * @param userinfo
     * @return
     */
    @RequestMapping("/social")
    public SocialUserInfo getSocialInfo(HttpServletRequest request){
        Connection<?> connectionFromSession = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
        SocialUserInfo socialUserInfo = new SocialUserInfo();
        socialUserInfo.setIamgeUrl(connectionFromSession.getImageUrl());
        socialUserInfo.setNickName(connectionFromSession.getDisplayName());
        ConnectionKey key = connectionFromSession.getKey();
        socialUserInfo.setProviderId(key.getProviderId());
        socialUserInfo.setProviderUserId(key.getProviderUserId());
        return socialUserInfo;
    }
}
